from flask import Flask, render_template
from flask_sock import Sock
import numpy as np
import cv2
import sys
import base64
import time

class Camera:
    def __init__(self):
        #self.camera = cv2.VideoCapture("/dev/v4l/by-path/platform-3f980000.usb-usb-0:1.1.3:1.0-video-index0")
        self.camera = cv2.VideoCapture(0)
        self.encode_params = [int(cv2.IMWRITE_JPEG_QUALITY), 70]
        self.image = cv2.imencode('.jpg', np.zeros((480, 640)), self.encode_params)[1].tobytes()

    def __del__(self):
        self.camera.release()

    def get_jpeg_image_bytes(self):
        ret, img = self.camera.read()
        res = cv2.imencode('.jpg', img, self.encode_params)[1].tobytes()
        return res

camera = Camera()

app = Flask(__name__)
app.config['TEMPLATES_AUTO_RELOAD'] = True

sock = Sock(app)

@app.route('/')
def index():
    return render_template('index.html')

@app.route('/api/control', methods=['POST'])
def api_manual_control():
    pass

@sock.route('/image')
def stream(sock):
    while True:
        sock.send(camera.get_jpeg_image_bytes())

if __name__ == "__main__":
    app.run(debug=False, host="0.0.0.0")
